﻿using log4net;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace SBarth.TheLionsShare
{
    public class Global : System.Web.HttpApplication
    {
        protected static readonly ILog log = LogManager.GetLogger(typeof(Global));

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
        }

        protected void Session_OnStart(object sender, EventArgs e)
        {
            string client = Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : "";
            string proxy = Request.ServerVariables["REMOTE_ADDR"] != null ? Request.ServerVariables["REMOTE_ADDR"] : "";
            string userAgent = Request.UserAgent != null ? Request.UserAgent : "";
            string referrer = Request.UrlReferrer != null ? Request.UrlReferrer.AbsolutePath : "";

            log.Info("Started session " + Session.SessionID + " - " +
                "Client Address:" + client + " | " +
                "Proxy Address:" + proxy + " | " +
                "UserAgent:" + userAgent + " | " +
                "UrlReferrer:" + referrer);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            log.Error("Application Started");
            Exception ex = Server.GetLastError().GetBaseException();
            log.Fatal(ex.GetType() + ": " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString());

            Server.ClearError();  // Don't propagate

            Response.Redirect(Request.Url.AbsoluteUri);

            // TODO: remove debugging info
            Response.Write("An unexpected error occurred, please contact your administrator <br/>" +
                           ex.GetType() + ": " + ex.Message.ToString() + "<br/>" + ex.StackTrace.ToString());
            
        }

        protected void Session_End(object sender, EventArgs e)
        {
            log.Info("Session " + Session.SessionID + " Terminated");
        }

        protected void Application_End(object sender, EventArgs e)
        {
            log.Info("Application Stopped");
        }
    }
}